package com.bwie.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import io.jsonwebtoken.*;

import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

import java.util.Date;

@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Autowired
    HttpServletRequest request;

    @Override
    public void insertFill(MetaObject metaObject) {

        String name="未知";
        try {
            String token = request.getHeader("token");
            if (token!=null){
                Claims body = Jwts.parser().setSigningKey("123456").parseClaimsJws(token).getBody();
                Integer userId = body.get("userId", Integer.class);
                name=""+userId;
            }
        } catch (Exception e) {

        }
        log.info("开始插入填充...");
        this.strictInsertFill(metaObject, "createdBy", String.class, name);
        this.strictInsertFill(metaObject, "createdTime", Date.class, new Date());
    }

    @Override
    public void updateFill(MetaObject metaObject) {

        String name="未知";
        try {
            String token = request.getHeader("token");
            if (token!=null){
                Claims body = Jwts.parser().setSigningKey("123456").parseClaimsJws(token).getBody();
                Integer userId = body.get("userId", Integer.class);
                name=""+userId;
            }

        } catch (Exception e) {

        }
        log.info("开始更新填充...");
        this.strictInsertFill(metaObject, "updatedBy", String.class, name);
        this.strictUpdateFill(metaObject, "updatedTime", Date.class, new Date());
    }
}